package com.san.metadata.dao;

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.san.base.dao.BaseManager;
import com.san.common.datasource.JdbcManager;
import com.san.common.utils.Constant;
import com.san.common.utils.Query;
import com.san.metadata.domain.DataSourceDO;
import com.san.metadata.domain.ManageTableDO;
import com.san.metadata.service.DataSourceService;
import com.san.metadata.service.ManageMetadataService;

/**
 * 管理元数据管理JDBC访问层
 * 
 * @author hulp
 *
 */
@Service
public class DataManageManager extends BaseManager {

	private static final Logger logger = LoggerFactory.getLogger(DataManageManager.class);

	@Autowired
	ManageMetadataService manageMetadataService;

	@Autowired
	DataSourceService dataSourceService;

	public List<Map<String, Object>> list(Query query, Long tableId) {
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getById(tableId);
		} catch (Exception e) {
			logger.error("获取管理元数据信息出错", e);
		}
		Long targetDataSource = manageTableDO.getTargetSourceId();
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(targetDataSource);
		} catch (Exception e) {
			logger.error("获取数据源信息出错", e);
		}
		JdbcManager jdbcManager = new JdbcManager();
		DruidPooledConnection conn = null;
		try {
			conn = this.getDBConnection(dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取数据库连接出错", e);
		}

		StringBuffer sql = new StringBuffer();

		int sourceType = dataSourceDO.getSourceType();
		switch (sourceType) {
		case Constant.SOURCE_TYPE_MYSQL:
			sql.append("select * from " + manageTableDO.getTargetTableName() + " where 1 = 1 ");
			if (query.get("keyWordName") != null && !"".equals(query.get("keyWordName")) && query.get("keyWord") != null
					&& !"".equals(query.get("keyWord"))) {
				sql.append("and " + query.get("keyWordName") + " = '" + query.get("keyWord") + "' ");
			}
			sql.append("limit " + query.getOffset() + "," + query.getLimit() + " ");
			break;

		case Constant.SOURCE_TYPE_ORACLE:
			sql.append("select * from (select rownum r," + manageTableDO.getTargetTableName() + ".* from "
					+ manageTableDO.getTargetTableName() + " where 1 = 1 ");
			if (query.get("keyWordName") != null && !"".equals(query.get("keyWordName")) && query.get("keyWord") != null
					&& !"".equals(query.get("keyWord"))) {
				sql.append("and " + query.get("keyWordName") + " = '" + query.get("keyWord") + "' ");
			}
			sql.append("and rownum <= " + (query.getOffset() + query.getLimit()) + " ");
			sql.append(") table_alias ");
			sql.append(" where table_alias.r > " + query.getOffset());
			break;
		default:
			break;
		}

		Object[] obj = {};
		List<Map<String, Object>> list = jdbcManager.executeQuery(conn, sql.toString(), obj);
		return list;
	}

	@SuppressWarnings("unchecked")
	public int count(Query query, Long tableId) {
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getById(tableId);
		} catch (Exception e) {
			logger.error("获取管理元数据信息出错", e);
		}
		Long targetDataSource = manageTableDO.getTargetSourceId();
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(targetDataSource);
		} catch (Exception e) {
			logger.error("获取数据源信息出错", e);
		}
		JdbcManager jdbcManager = new JdbcManager();
		DruidPooledConnection conn = null;
		try {
			conn = this.getDBConnection(dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取数据库连接出错", e);
		}

		StringBuffer sql = new StringBuffer();
		int sourceType = dataSourceDO.getSourceType();
		switch (sourceType) {
		case Constant.SOURCE_TYPE_MYSQL:
			sql.append("select count(1) from " + manageTableDO.getTargetTableName() + " where 1 = 1 ");
			if (query.get("keyWordName") != null && !"".equals(query.get("keyWordName")) && query.get("keyWord") != null
					&& !"".equals(query.get("keyWord"))) {
				sql.append("and " + query.get("keyWordName") + " = '" + query.get("keyWord") + "' ");
			}
			break;

		case Constant.SOURCE_TYPE_ORACLE:
			sql.append("select count(1) from " + manageTableDO.getTargetTableName() + " where 1 = 1 ");
			if (query.get("keyWordName") != null && !"".equals(query.get("keyWordName")) && query.get("keyWord") != null
					&& !"".equals(query.get("keyWord"))) {
				sql.append("and " + query.get("keyWordName") + " = '" + query.get("keyWord") + "' ");
			}
			break;
		default:
			break;
		}

		Object[] obj = {};
		List<?> list = jdbcManager.executeQuery(conn, sql.toString(), obj);
		return ((Long) (((Map<String, Object>) list.get(0)).get("count(1)"))).intValue();
	}

	public List<Map<String, Object>> getByrepeatMark(Long tableId, String repeatMark) {
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getById(tableId);
		} catch (Exception e) {
			logger.error("获取管理元数据信息出错", e);
		}
		Long targetDataSource = manageTableDO.getTargetSourceId();
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(targetDataSource);
		} catch (Exception e) {
			logger.error("获取数据源信息出错", e);
		}
		JdbcManager jdbcManager = new JdbcManager();
		DruidPooledConnection conn = null;
		try {
			conn = this.getDBConnection(dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取数据库连接出错", e);
		}

		StringBuffer sql = new StringBuffer();

		int sourceType = dataSourceDO.getSourceType();
		switch (sourceType) {
		case Constant.SOURCE_TYPE_MYSQL:
			sql.append("select * from " + manageTableDO.getTargetTableName() + " where 1 = 1 ");
			sql.append("and REPEAT_MARK = '" + repeatMark + "'");
			break;

		case Constant.SOURCE_TYPE_ORACLE:
			sql.append("select * from " + manageTableDO.getTargetTableName() + " where 1 = 1 ");
			sql.append("and REPEAT_MARK = '" + repeatMark + "'");
			break;
		default:
			break;
		}

		Object[] obj = {};
		List<Map<String, Object>> list = jdbcManager.executeQuery(conn, sql.toString(), obj);
		return list;
	}

	public boolean remove(Long tableId, String repeatMark) {
		ManageTableDO manageTableDO = null;
		try {
			manageTableDO = manageMetadataService.getById(tableId);
		} catch (Exception e) {
			logger.error("获取管理元数据信息出错", e);
		}
		Long targetDataSource = manageTableDO.getTargetSourceId();
		DataSourceDO dataSourceDO = null;
		try {
			dataSourceDO = (DataSourceDO) dataSourceService.getById(targetDataSource);
		} catch (Exception e) {
			logger.error("获取数据源信息出错", e);
		}
		JdbcManager jdbcManager = new JdbcManager();
		DruidPooledConnection conn = null;
		try {
			conn = this.getDBConnection(dataSourceDO.getSourceCode());
		} catch (Exception e) {
			logger.error("获取数据库连接出错", e);
		}

		StringBuffer sql = new StringBuffer();

		int sourceType = dataSourceDO.getSourceType();
		switch (sourceType) {
		case Constant.SOURCE_TYPE_MYSQL:
			sql.append(
					"delete from " + manageTableDO.getTargetTableName() + " where REPEAT_MARK = '" + repeatMark + "'");
			break;
		case Constant.SOURCE_TYPE_ORACLE:
			sql.append(
					"delete from " + manageTableDO.getTargetTableName() + " where REPEAT_MARK = '" + repeatMark + "'");
			break;
		default:
			break;
		}

		Object[] obj = {};
		boolean flag = jdbcManager.executeSQL(conn, sql.toString(), obj);
		return flag;
	}

}
